package org.lcc.Controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import org.lcc.Service.DashboardService;
import org.lcc.model.dto.CertificateTemplateDTO;
import org.lcc.model.dto.CertificateIssuanceDTO;
import org.lcc.util.ApiResponseMe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.List;

@RestController
@RequestMapping("/dashboard")
@Tag(name = "证书", description = "证书相关的接口")
@Slf4j
public class DashboardController {

    @Autowired
    private DashboardService dashboardService;


    @GetMapping("/overview")
    @Operation(summary = "获取系统概览数据")
    public ApiResponseMe getSystemOverview() {
        try {
            Map<String, Object> overview = dashboardService.getSystemOverview();
            return ApiResponseMe.success(overview);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponseMe.error(500, "获取系统概览数据失败");
        }
    }

    @PostMapping("/certificate/template/save")
    public ApiResponseMe saveCertificateTemplate(@RequestBody CertificateTemplateDTO templateDTO) {
        try {
            dashboardService.saveCertificateTemplate(templateDTO);
            return ApiResponseMe.success(null);
        } catch (Exception e) {
            log.error("保存证书模板失败", e);
            return ApiResponseMe.error(400,"保存证书模板失败: " + e.getMessage());
        }
    }

    @GetMapping("/certificate/template/list")
    @Operation(summary = "获取用户创建的证书模板列表")
    public ApiResponseMe getTemplatesByCreator(@RequestParam String creatorId) {
        try {
            return ApiResponseMe.success(dashboardService.getTemplatesByCreator(creatorId));
        } catch (Exception e) {
            log.error("获取证书模板列表失败", e);
            return ApiResponseMe.error(400, "获取证书模板列表失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/certificate/template/{templateId}")
    @Operation(summary = "删除证书模板")
    public ApiResponseMe deleteTemplate(@PathVariable Integer templateId) {
        try {
            dashboardService.deleteTemplate(templateId);
            return ApiResponseMe.success(null);
        } catch (Exception e) {
            log.error("删除证书模板失败", e);
            return ApiResponseMe.error(400, "删除证书模板失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/certificate/template/preview/{templateId}")
    @Operation(summary = "获取证书模板预览图")
    public ResponseEntity<byte[]> getTemplatePreview(@PathVariable Integer templateId) {
        try {
            byte[] previewImage = dashboardService.generateTemplatePreview(templateId);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            return new ResponseEntity<>(previewImage, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("获取证书模板预览失败", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/certificate/exam/list/{schoolNumber}")
    @Operation(summary = "获取已结束的考试列表")
    public ApiResponseMe getFinishedExams(
            @PathVariable String schoolNumber,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            return ApiResponseMe.success(dashboardService.getFinishedExams(schoolNumber,current, size));
        } catch (Exception e) {
            log.error("获取已结束考试列表失败", e);
            return ApiResponseMe.error(400, "获取已结束考试列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/certificate/exam/{examId}")
    @Operation(summary = "获取考试详情")
    public ApiResponseMe getExamDetail(@PathVariable Integer examId) {
        try {
            return ApiResponseMe.success(dashboardService.getExamDetail(examId));
        } catch (Exception e) {
            log.error("获取考试详情失败", e);
            return ApiResponseMe.error(400, "获取考试详情失败: " + e.getMessage());
        }
    }

    @PostMapping("/certificate/issue")
    @Operation(summary = "颁发证书", description = "根据考试ID、模板ID和条件颁发证书")
    public ApiResponseMe issueCertificates(@RequestBody CertificateIssuanceDTO issuanceDTO) {
        try {
            log.info("开始颁发证书，参数: {}", issuanceDTO);
            List<Map<String, Object>> issuedCertificates = dashboardService.issueCertificates(issuanceDTO);
            log.info("证书颁发成功，共颁发 {} 份证书", issuedCertificates.size());
            return ApiResponseMe.success(issuedCertificates);
        } catch (Exception e) {
            log.error("证书颁发失败", e);
            return ApiResponseMe.error(400, "证书颁发失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/certificate/preview/issue")
    @Operation(summary = "预览证书颁发", description = "根据考试ID、模板ID和条件预览将要颁发的证书")
    public ApiResponseMe previewIssueCertificates(
            @RequestParam Integer examId,
            @RequestParam Integer templateId,
            @RequestParam Integer passThreshold,
            @RequestParam(required = false) String content,
            @RequestParam(required = false) String issuer,
            @RequestParam(required = false) String issueDate) {
        try {
            log.info("预览证书颁发, examId: {}, templateId: {}, passThreshold: {}, content: {}, issuer: {}, issueDate: {}", 
                    examId, templateId, passThreshold, content, issuer, issueDate);
            
            CertificateIssuanceDTO issuanceDTO = new CertificateIssuanceDTO();
            issuanceDTO.setExamId(examId);
            issuanceDTO.setTemplateId(templateId);
            issuanceDTO.setPassThreshold(passThreshold);
            issuanceDTO.setContent(content);
            issuanceDTO.setIssuer(issuer);
            issuanceDTO.setIssueDate(issueDate);
            
            List<Map<String, Object>> previewData = dashboardService.previewCertificateIssuance(issuanceDTO);
            log.info("证书预览成功，共有 {} 份证书将被颁发", previewData.size());
            return ApiResponseMe.success(previewData);
        } catch (Exception e) {
            log.error("证书预览失败", e);
            return ApiResponseMe.error(400, "证书预览失败: " + e.getMessage());
        }
    }

    @GetMapping("/certificate/student/list")
    @Operation(summary = "获取学生证书列表", description = "根据学生ID获取其所有证书")
    public ApiResponseMe getStudentCertificates(
            @RequestParam String studentId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        try {
            log.info("获取学生证书列表, studentId: {}, pageNum: {}, pageSize: {}, keyword: {}", 
                    studentId, pageNum, pageSize, keyword);
            return ApiResponseMe.success(dashboardService.getStudentCertificates(studentId, pageNum, pageSize, keyword));
        } catch (Exception e) {
            log.error("获取学生证书列表失败", e);
            return ApiResponseMe.error(400, "获取学生证书列表失败: " + e.getMessage());
        }
    }
} 